import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Redirect, Switch } from 'dva/router';
import { getRoutes } from '../utils/utils';
import Authorized from '../utils/Authorized';
import { getMenuData } from '../common/menu';

const { AuthorizedRoute } = Authorized;

/**
 * 根据菜单取得重定向地址.
 */
const redirectData = [];
const getRedirect = (item) => {
  if (item && item.children) {
    if (item.children[0] && item.children[0].path) {
      redirectData.push({
        from: `${item.path}`,
        to: `${item.children[0].path}`,
      });
      item.children.forEach((children) => {
        getRedirect(children);
      });
    }
  }
};
getMenuData().forEach(getRedirect);


class BasicLayout extends React.PureComponent {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  };
  getChildContext() {
    const { location, routerData } = this.props;
    return {
      location,
      breadcrumbNameMap: routerData,
    };
  }
  componentDidMount() {
  }
  getBashRedirect = () => {
    // According to the url parameter to redirect
    // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
    const urlParams = new URL(window.location.href);

    const redirect = urlParams.searchParams.get('redirect');
    // Remove the parameters in the url
    if (redirect) {
      urlParams.searchParams.delete('redirect');
      window.history.replaceState(null, 'redirect', urlParams.href);
    } else {
      return '/';
    }
    return redirect;
  };
  render() {
    const {
      routerData, match,
    } = this.props;
    const bashRedirect = this.getBashRedirect();
    return (
      <Switch>
        {
          redirectData.map(item =>
            <Redirect key={item.from} exact from={item.from} to={item.to} />
          )
        }
        {
          getRoutes(match.path, routerData).map(item =>
            (
              <AuthorizedRoute
                key={item.key}
                path={item.path}
                component={item.component}
                exact={item.exact}
                authority={item.authority}
                redirectPath="/"
              />
            )
          )
        }
        <Redirect exact from="/" to={bashRedirect} />
      </Switch>
    );
  }
}

export default connect(({ global }) => ({
  collapsed: global.collapsed,
}))(BasicLayout);
